package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service/dto"
)

type SysWxStudent struct {
	service.Service
}

func (e *SysWxStudent) Insert(c *dto.SysWxStudentInsertReq, student *dto.SysStudentInsertReq) (lastId int, err error) {
	var data models.SysWxStudent
	var studentData models.SysStudent
	c.Generate(&data)
	student.Generate(&studentData)
	transactionErr := e.Orm.Transaction(func(tx *gorm.DB) error {
		err = tx.Create(&data).Error
		if err != nil {
			return err
		}
		err = tx.Create(&studentData).Error
		if err != nil {
			return err
		}
		return nil
	})
	if transactionErr != nil {
		return 0, transactionErr
	}

	go func(studentID int) {
		e.Orm.Model(&data).Update("student_id", studentID)
	}(studentData.Id)

	return studentData.Id, nil
}

func (e *SysWxStudent) Update(model models.SysWxStudent) error {
	var err error
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil

}
